<?php

namespace Addons\BLConn\Controller;

use Home\Controller\AddonsController;
use User\Api\UserApi;


class BLConnController extends AddonsController {
    // 通用插件的列表模型
    function _initialize() {
        parent::_initialize();

        $controller = strtolower ( _CONTROLLER );

        $res ['title'] = '会员管理';
        $res ['url'] = addons_url ( 'BLConn://BLConn/lists' );
        $res ['class'] = $controller == 'blconn' ? 'current' : '';
        $nav [] = $res;

        $res ['title'] = '积分总记录';
        $res ['url'] = addons_url ( 'BLConn://ScoreLog/lists' );
        $res ['class'] = $controller == 'scorelog' ? 'current' : '';
        $nav [] = $res;

        $this->assign ( 'nav', $nav );
    }


    public function lists() {
        $userModel = M('user');
        $today = strtotime('today');
        //检查店家到期状态
        M('member')->where("uid != 1 AND status = 1 AND (adminValidDate < $today OR adminValidDate IS NULL)")->setField('status', 0);

        //根据字段排序
        $listSort = I('list_sort', 0);
        if(empty($listSort)) {
            $sessionListSort = session('list_sort');
            if(!empty($sessionListSort)) {
                $listSort = $sessionListSort;
            } else {
                $listSort = 1;
            }
        }
        session('list_sort', $listSort);
        $this->assign('list_sort', $listSort);
        $order = $listSort == 1 ? 'nickname asc' : 'registerTime desc';

        $model = $this->getModel('user');

        $page = I('p', 1, 'intval'); // 默认显示第一页数据
        // 解析列表规则
        $list_data = $this->_list_grid($model);
        $grids = $list_data ['list_grids'];
        $fields = $list_data ['fields'];

        // 搜索条件
        $token = get_token();
        $map = "token='$token'";

        // 关键字搜索
        $this->assign('placeholder', "请输入ID或昵称");
        $key = 'search_key';
        $this->assign('search_key', $key);

        if(!empty ($_REQUEST[$key])) {
            $map .= " AND (id = '{$_REQUEST[$key]}' OR nickname like '%{$_REQUEST[$key]}%')";
            //$order = "CASE id WHEN {$_REQUEST[$key]} THEN 1 ELSE 0 END desc, ".$order;
            unset ($_REQUEST [$key]);
        }

        $row = empty ($model ['list_row']) ? 20 : $model ['list_row'];

        // 读取模型数据列表
        empty ($fields) || in_array('id', $fields) || array_push($fields, 'id');
        $data = $userModel->field(empty ($fields) ? true : $fields)->where($map)->order($order)->page($page, $row)->select();

        /* 查询记录总数 */
        $count = $userModel->where($map)->count();
        $list_data ['list_data'] = $data;

        // 分页
        if($count > $row) {
            $page = new \Think\Page ($count, $row);
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $list_data ['_page'] = $page->show();
        }

        $operateIndex = count($list_data['list_grids']) - 1;    //操作项索引
        $config = getAddonConfig('BLCConfig');
        $normal_tips = '当前配置用户保底积分：'.$config['lockScore'];

        if(is_administrator()) {    //超级管理员
            $LOVE_INTEGRAL_TANK = M('Config')->where("name='LOVE_INTEGRAL_TANK'")->getField('value');
            $normal_tips .= '，爱心积分罐：'.$LOVE_INTEGRAL_TANK." <a href='".U('clearLoveTank')."'>清除</a>";
            /*$top_more_button[] = array('title' => '注册店家', 'url' => U('addAdmin'));
            $this->assign('top_more_button', $top_more_button);*/

        } else {    //店家
            $list_data['list_grids'][$operateIndex]['href'] = 'presentScore?id=[id]|赠送积分';

            //加入可赠送积分提示
            $adminInfo = get_admin_info();
            $adminScore = $userModel->where("id='{$adminInfo['blcUserId']}'")->getField('score');
            $adminScore = intval($adminScore);
            $normal_tips .= "，您的关联会员ID：{$adminInfo['blcUserId']}，可赠送积分：{$adminScore}";

            //加入积分回收权提示
            if($adminInfo['reclaimValidDate'] >= $today) { //在回收权期间
                $list_data['list_grids'][$operateIndex]['href'] .= ',reclaimScore?id=[id]|回收积分,showOrder?uid=[id]|查看订单';
                $normal_tips .= '，可回收积分： '.$adminInfo['enableReclaimScore'];
            }
        }

        $list_data['list_grids'][$operateIndex]['href'] .= ',userScoreLog?id=[id]|积分记录';
        $this->assign($list_data);
        $this->assign('add_button', false);
        $this->assign('del_button', false);
        $this->assign('normal_tips', $normal_tips);

        $this->display();
    }

    public function userScoreLog() {
        $url = addons_url("BLConn://ScoreLog/lists", array('id' => I('id')));
        redirect($url);
    }

    // 通用插件的编辑模型
    /*public function edit() {
        parent::common_edit('user');
    }*/

    // 通用插件的增加模型
    /*public function add()
    {
        parent::common_add('user');
    }*/

    // 通用插件的删除模型
    /*public function del()
    {
        parent::common_del('user');
        //删除店家时须同时禁用对应的后台系统会员账号
    }*/

    // 充值积分
    public function rechargeScore() {
        $userModel = M('user');
        $scoreLogModel = M('score_log');

        $id = I('id');
        $id || $this->error('无效的会员ID', U('lists'));
        $userData = $userModel->where("id=$id")->find();
        $userData || $this->error('无效的会员ID', U('lists'));

        is_administrator() || $this->error('店家无充值积分的权限');

        if(IS_POST) {
            $changeScore = I('changeScore');
            preg_match('/^[1-9][0-9]*$/', $changeScore) || $this->error('无效的充值积分');

            $result = $userModel->where("id=$id")->setInc('score', $changeScore);   //增加会员积分
            if($result) {
                $userLog = array(
                    'uid' => $id,
                    'score' => $changeScore,
                    'type' => 1,
                    'detail' => '管理员充值'.$changeScore.'分',
                    'adminId' => is_login(),
                    'createTime' => time()
                );
                $scoreLogModel->add($userLog); //积分记录

                $this->success('充值积分成功', U('lists'));
            } else {
                $this->error('充值积分失败');
            }

        } else {
            $this->assign('user', $userData);
            $this->display();
        }
    }

    // 回收积分
    public function reclaimScore() {
        $userModel = M('user');
        $orderModel = M('order');

        $adminId = is_login();
        empty($adminId) && $this->error('当前登录异常', U('lists'));

        $adminInfo = get_admin_info();
        //检查店家是否有回收权
        if(!is_administrator()) {
            if($adminInfo['reclaimValidDate'] < strtotime('today')) { //不在回收权期间
                $this->error('您当前没有积分回收权', U('lists'));
            }
        }

        //检查数据
        $id = I('id');
        $id || $this->error('无效的会员ID', U('lists'));
        $userData = $userModel->where("id=$id")->find();
        $userData || $this->error('无效的会员ID', U('lists'));
        $checkUnConfirmOrder = $orderModel->where("uid=$id and status=0")->count();
        $checkUnConfirmOrder && $this->error('该会员尚有未确认订单', U('lists'));

        if(IS_POST) {
            $changeScore = I('changeScore');
            preg_match('/^[1-9][0-9]*$/', $changeScore) || $this->error('无效的回收积分');
            $detail = I('detail');
            $detail || $this->error('回收详情不能为空');

            //加入店家可扣除的积分限制
            if(!is_administrator()) {
                //计算店家可回收积分，除去了待确认订单中冻结的积分
                $adminLockScore = $orderModel->where("status=0 and adminId=$adminId")->sum('score');
                $enableReclaimScore = $adminInfo['enableReclaimScore'] - $adminLockScore;
                ($changeScore <= $enableReclaimScore) || $this->error('可回收积分不足');
            }

            //保底积分需求
            $config = getAddonConfig('BLCConfig');
            if(($userData['score'] - $config['lockScore']) < $changeScore) {
                $this->error('会员积分不足');
            }

            //写入订单，用户先确认再扣分需求
            $orderData = array(
                'uid' => $id,
                'score' => $changeScore,
                'detail' => $detail,
                'adminId' => $adminId,
                'status' => 0,    //待确认
                'createTime' => time()
            );
            $result = $orderModel->add($orderData);
            if($result) {
                $this->success('回收积分成功，请等待用户确认', U('showOrder', array('uid' => $id)));
            } else {
                $this->error('回收积分失败');
            }

        } else {
            $this->assign('user', $userData);
            $this->display();
        }
    }

    // 赠送积分
    public function presentScore() {
        $userModel = M('user');
        $scoreLogModel = M('score_log');

        $adminId = is_login();
        empty($adminId) && $this->error('当前登录异常', U('lists'));

        $id = I('id');
        $id || $this->error('无效的会员ID', U('lists'));
        $userData = $userModel->where("id=$id")->find();
        $userData || $this->error('无效的会员ID', U('lists'));

        is_administrator() && $this->error('您不是店家');
        $adminInfo = get_admin_info();
        if(empty($adminInfo['blcUserId'])) {
            $this->error('您没有关联会员ID，请联系管理员', U('lists'));
        } elseif($adminInfo['blcUserId'] == $id) {
            $this->error('不能给自己赠送积分', U('lists'));
        }

        if(IS_POST) {
            $changeScore = I('changeScore');
            preg_match('/^[1-9][0-9]*$/', $changeScore) || $this->error('无效的赠送积分');

            $adminScore = $userModel->where("id='{$adminInfo['blcUserId']}'")->getField('score');
            $adminScore < $changeScore && $this->error('当前店家积分不足', U('lists'));

            $result = $userModel->where("id='$id'")->setInc('integralTank', $changeScore);   //增加会员积分
            if($result) {
                //判断会员是否已经达到积分罐上限
                checkIntegralTank($id);

                $userModel->where("id='{$adminInfo['blcUserId']}'")->setDec('score', $changeScore); //减少管理员积分
                $adminLog = array(
                    'uid' => $adminInfo['blcUserId'],
                    'score' => $changeScore,
                    'type' => 2,    //支出
                    'detail' => '店家赠送积分操作支出'.$changeScore.'分',
                    'adminId' => $adminId,
                    'createTime' => time()
                );
                $scoreLogModel->add($adminLog); //积分记录
                $this->success('赠送积分成功', U('lists'));
            } else {
                $this->error('赠送积分失败');
            }

        } else {
            $this->assign('user', $userData);
            $this->display();
        }
    }

    //一键升级为店家
    /*public function oneKeyUpdate() {
        $id = I('id');
        $userModel = M('user');

        $id || $this->error('无效的会员ID', U('lists'));
        $userData = $userModel->where("id=$id")->find();
        $userData || $this->error('无效的会员ID', U('lists'));
        $userData['isAdmin'] && $this->error('该会员已是店家', U('lists'));

        if(IS_POST) {
            $adminValidDate = I('adminValidDate');
            $adminValidDate || $this->error('管理员到期日期不能为空');
            $adminValidDate = strtotime($adminValidDate);
            $today = strtotime(date('Y-m-d'));
            $adminValidDate <= $today && $this->error('管理员到期日期不能早于今天');

            // 管理员用户存在则更改状态
            $user_mdl = M('member');
            $user_info = $user_mdl->where("status=0 and nickname='".$userData['phone']."'")->find();
            if($user_info) {
                $res = $user_mdl->where("nickname='".$userData['phone']."'")->setField('status', 1);
                if($res) {
                    $data = array(
                        'isAdmin' => 1,
                        'adminValidDate' => $adminValidDate,
                    );
                    $result = $userModel->where("id=$id")->save($data);
                    if($result) {
                        $this->success('升级店家成功', U('lists'));
                    } else {
                        $user_mdl->where("nickname='".$userData['phone']."'")->setField('status', 0);  //重新禁用后台用户
                        $this->error('升级店家失败');
                    }
                } else {
                    $this->error('升级店家失败');
                }
            }

            // 管理员用户不存在则注册新用户
            $userApi = new UserApi();
            $uid = $userApi->register($userData['phone'], $userData['password'], $userData['phone'].'@139.com', $userData['phone'], $userData['openid'], $userData['token']);
            if(!$uid) {
                $this->error('升级店家失败');
            } else {
                $data = array(
                    'isAdmin' => 1,
                    'adminValidDate' => $adminValidDate,
                    'adminId' => $uid
                );
                $result = $userModel->where("id=$id")->save($data);
                if($result) {
                    $this->success('升级店家成功', U('lists'));
                } else {
                    //$user_mdl->where("nickname='" . $userData['phone'] . "'")->setField('status', 0);  //重新禁用后台用户
                    $this->error('升级店家失败');
                }
            }
        } else {
            $this->assign('user', $userData);
            $this->display();
        }
    }*/

    //积分记录
    /*public function scoreLog()
    {
        $map ['uid'] = I('id');
        session('common_condition', $map);
        $this->assign('add_button', false);
        $this->assign('del_button', false);
        $this->assign('search_button', false);
        parent::common_lists('score_log', 0, 'lists');
    }*/

    //查看订单
    public function showOrder() {
        $this->assign('add_button', false);
        $this->assign('del_button', false);
        $this->assign('search_button', false);
        parent::common_lists('order', 0, 'lists');
    }

    //取消订单
    public function cancelOrder() {
        $id = I('id');
        $result = M('order')->where("id=$id and status=0")->delete();
        if($result) {
            $this->success('取消订单成功');
        } else {
            $this->error('取消失败，订单可能已确认');
        }
    }

    //开通回收权限
    /*public function openReclaim() {
        $id = I('id');
        $userModel = M('user');

        $id || $this->error('无效的会员ID', U('lists'));
        $userData = $userModel->where("id=$id")->find();
        $userData || $this->error('无效的会员ID', U('lists'));
        $userData['isAdmin'] || $this->error('该会员不是店家', U('lists'));
        $userData['reclaimEndTime'] > time() && $this->error('该店家已开通回收权', U('lists'));

        if(IS_POST) {
            $reclaimStartTime = I('reclaimStartTime');
            $reclaimStartTime || $this->error('回收权开始时间不能为空');
            $reclaimEndTime = I('reclaimEndTime');
            $reclaimEndTime || $this->error('回收结束时间不能为空');
            $enableReclaimScore = I('enableReclaimScore');
            $enableReclaimScore || $this->error('可回收积分不能为空');

            $reclaimStartTime = strtotime($reclaimStartTime);
            $reclaimEndTime = strtotime($reclaimEndTime);

            $reclaimStartTime < time() && $this->error('回收权开始时间不能早于当前时间');
            $reclaimEndTime <= $reclaimStartTime && $this->error('回收权结束时间必须晚于开始时间');
            $reclaimEndDate = strtotime(date('Y-m-d', $reclaimEndTime));
            $reclaimEndDate <= $userData['adminValidDate'] || $this->error('回收权结束时间不能晚于管理员到期时间');

            $data = array(
                'reclaimStartTime' => $reclaimStartTime,
                'reclaimEndTime' => $reclaimEndTime,
                'enableReclaimScore' => $enableReclaimScore
            );
            $result = $userModel->where("id=$id")->save($data);
            if($result) {
                $this->success('开通回收权成功', U('lists'));
            } else {
                $this->error('开通回收权失败');
            }

        } else {
            $this->assign('user', $userData);
            $this->display();
        }
    }*/

    //清除爱心积分罐
    public function clearLoveTank() {
        if(!is_administrator()) { //非超级管理员
            $this->error('只有超级管理员才能清除！');
        }

        M('Config')->where("name='LOVE_INTEGRAL_TANK'")->setField('value', 0);
        $this->success('清除成功！');
    }

    //注册中级管理员（后台用户）
    /*public function addAdmin() {
        if(IS_POST) {
            $username = I('username');
            $password = I('password');
            $repassword = I('repassword');
            $email = I('email');

            // 检测密码
            if($password != $repassword) {
                $this->error('密码和重复密码不一致！');
            }

            // 调用注册接口注册用户
            $User = new UserApi;
            $uid = $User->register($username, $password, $email);
            if(0 < $uid) { //注册成功
                $user = array('uid' => $uid, 'nickname' => $username, 'status' => 1);
                if(!M('Member')->add($user)) {
                    $this->error('中级管理员添加失败！');
                } else {
                    $this->success('中级管理员添加成功！', U('lists'));
                }
            } else { //注册失败，显示错误信息
                $this->error($this->showRegError($uid));
            }
        } else {
            $this->meta_title = '注册中级管理员';
            $this->display();
        }
    }*/

    /**
     * 获取用户注册错误信息
     * @param  integer $code 错误编码
     * @return string        错误信息
     */
    /*private function showRegError($code = 0) {
        switch($code) {
            case -1:
                $error = '用户名长度必须在16个字符以内！';
                break;
            case -2:
                $error = '用户名被禁止注册！';
                break;
            case -3:
                $error = '用户名被占用！';
                break;
            case -4:
                $error = '密码长度必须在6-30个字符之间！';
                break;
            case -5:
                $error = '邮箱格式不正确！';
                break;
            case -6:
                $error = '邮箱长度必须在1-32个字符之间！';
                break;
            case -7:
                $error = '邮箱被禁止注册！';
                break;
            case -8:
                $error = '邮箱被占用！';
                break;
            case -9:
                $error = '手机格式不正确！';
                break;
            case -10:
                $error = '手机被禁止注册！';
                break;
            case -11:
                $error = '手机号被占用！';
                break;
            default:
                $error = '未知错误';
        }

        return $error;
    }*/
}
